const fs = require('fs');
const path = require('path');

// 从环境变量获取参数（添加默认值处理）
const CONFIG = {
  projectPath: process.env.PROJECT_PATH || 'D:/Work/Jenkins_Test',
  replacements: {
    appName: process.env.NEW_GAME_NAME || '默认游戏名',
    version: process.env.NEW_VERSION_NUMBER || '1.0.0',
    platId: process.env.NEW_PLAT_ID || '1',
    SERVER_URL: process.env.NEW_SERVER_URL || 'http://default.server' // 若 GameDef.ts 无此项，可注释
  }
};

const TS_FILE = path.join(CONFIG.projectPath, 'assets', 'scripts', 'GameDef.ts');

// 修正后的正则匹配
const VARIABLE_PATTERNS = {
  appName: /(?:public\s+static\s+)?appName\s*[:=]\s*(?:"([^"]*)"|'([^']*)'|`([^`]*)`)/,
  version: /(?:public\s+static\s+)?version\s*[:=]\s*(?:"([^"]*)"|'([^']*)'|`([^`]*)`)/,
  platId: /(?:^|\s)(?:public\s+static\s+)?platId\s*[:=]\s*(?:"([^"]*)"|'([^']*)'|`([^`]*)`)/m,
  SERVER_URL: /(?:public\s+static\s+)?SERVER_URL\s*[:=]\s*(?:"([^"]*)"|'([^']*)'|`([^`]*)`)/,
};

try {
  // 显式指定 utf8 编码读取文件
  let content = fs.readFileSync(TS_FILE, 'utf8');

  // 执行变量替换
  Object.entries(CONFIG.replacements).forEach(([key, value]) => {
    if (!VARIABLE_PATTERNS[key]) {
      throw new Error(`未知变量: ${key}。可用变量: ${Object.keys(VARIABLE_PATTERNS)}`);
    }
    const pattern = VARIABLE_PATTERNS[key];
    if (!content.match(pattern)) {
      console.warn(`未找到变量 ${key} 在文件中，跳过替换`);
      return;
    }
    content = content.replace(pattern, (match, p1, p2, p3, p4) => {
      const quote = p1 !== undefined ? '"' : p2 !== undefined ? "'" : '`';
      return match.replace(p1 || p2 || p3 || p4, value);
    });
  });

  // 写入时显式指定 utf8 编码，无 BOM
  fs.writeFileSync(TS_FILE, content, 'utf8');

  console.log('变量替换成功');

  const verifyContent = fs.readFileSync(TS_FILE, 'utf8');
  Object.entries(CONFIG.replacements).forEach(([key, value]) => {
    if (!verifyContent.includes(value)) {
      throw new Error(`验证失败: 变量 ${key} 未被替换为 ${value}`);
    }
  });
} catch (error) {
  console.error('替换失败:', error.message);
  process.exit(1);
}
